/**
 * Copyright (c) 2017-2020
 * Subnew All Rights Reserved
 * Subnew is  nick name  of JoseanLuo ,This software is the confidential and proprietary information of JoseanLuo
 * You shall not disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into with JoseanLuo
 *
 * @email:joseanluo@gmail.com
 */
package com.subnew.apm.common.logger;

import com.subnew.apm.common.logger.system.SystemLoggerAdapter;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

/**
 * @author JoseanLuo
 * @date 2017/10/25
 * @email joseanluo@gmail.com
 */
public class LoggerFactory {
    private LoggerFactory() {
    }

    private static volatile LoggerAdapter LOGGER_ADAPTER;

    private static final ConcurrentMap<String, BaseLogger> LOGGERS = new ConcurrentHashMap<String, BaseLogger>();
    static {
        setLoggerAdapter(new SystemLoggerAdapter());
    }
    /**
     * 设置日志输出器供给器
     */
    public static void setLoggerAdapter(LoggerAdapter loggerAdapter) {
        if (loggerAdapter != null) {
            Logger logger = loggerAdapter.getLogger(LoggerFactory.class.getName());
            logger.info("-[APM] using logger: " + loggerAdapter.getClass().getName());
            LoggerFactory.LOGGER_ADAPTER = loggerAdapter;
            for (Map.Entry<String, BaseLogger> entry : LOGGERS.entrySet()) {
                entry.getValue().setLogger(LOGGER_ADAPTER.getLogger(entry.getKey()));
            }
        }
    }

    /**
     * 获取日志输出器
     */
    public static Logger getLogger(Class<?> key) {
        BaseLogger logger = LOGGERS.get(key.getName());

        if (logger == null) {
            LOGGERS.putIfAbsent(key.getName(), new BaseLogger(LOGGER_ADAPTER.getLogger(key)));
            logger = LOGGERS.get(key.getName());
        }
        return logger;
    }

    /**
     * 获取日志输出器
     */
    public static Logger getLogger(String key) {
        BaseLogger logger = LOGGERS.get(key);
        if (logger == null) {
            LOGGERS.putIfAbsent(key, new BaseLogger(LOGGER_ADAPTER.getLogger(key)));
            logger = LOGGERS.get(key);
        }
        return logger;
    }

    /**
     * 动态设置输出日志级别
     */
    public static void setLevel(Level level) {
        LOGGER_ADAPTER.setLevel(level);
    }

    /**
     * 获取日志级别
     */
    public static Level getLevel() {
        return LOGGER_ADAPTER.getLevel();
    }


}
